package com.spx.core.ui.views;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

import com.spx.core.CoreActivator;
import com.spx.core.services.ActivityLabel;
import com.spx.core.services.SecurityListener;
import com.spx.core.services.SecurityService;
import com.spx.core.types.Role;
import com.spx.core.types.User;
import com.spx.kernel.types.ModelType;

/**
 
 */

@ActivityLabel(name="view-users")
public class UserView extends com.spx.core.ui.views.SecureViewPart
{

	SecurityService ss;
	final UserViewContentProvider userViewContentProvider = new UserViewContentProvider();

	/**
	 * The ID of the view as specified by the extension.
	 */

	public static final String ID = "com.spx.core.ui.views.UserView";

	private TreeViewer viewer;

	// private Activity addUserAction;

	/*
	 * The content provider class is responsible for providing objects to the
	 * view. It can wrap existing objects in adapters or simply return objects
	 * as-is. These objects may be sensitive to the current input of the view,
	 * or ignore it and always show the same content (like Task List, for
	 * example).
	 */

	class UserViewContentProvider extends com.spx.core.services.SecurityListenerAdapter implements ITreeContentProvider, IStructuredContentProvider,
			SecurityListener
	{

		private Viewer viewer;

		private final List<User> users = new ArrayList<User>();

		public void inputChanged(Viewer v, Object oldInput, Object newInput)
		{
			viewer = v;

		}

		public void dispose()
		{
		}
		
		@Override
		public void change(ModelType type)
		{

			if (viewer != null && viewer.getControl().isDisposed() == false)
			{
				viewer.refresh();
			}
		}

		public Object[] getElements(Object parent)
		{

			users.clear();
			final Set<User> allUsers = ss.fetchAllUsers(0, Integer.MAX_VALUE);
			users.addAll(allUsers);
			return users.toArray();

		}

		
		@Override
		public Object[] getChildren(Object parentElement)
		{
			Object result[] = new Object[] {};
			if (parentElement instanceof Role)
			{
				result = ((Role) parentElement).getActions().toArray();
			} else if (parentElement instanceof User)
			{
				result = ((User) parentElement).getRoles().toArray();
			}

			return result;
		}

		@Override
		public Object getParent(Object element)
		{
			
			return null;
		}

		@Override
		public boolean hasChildren(Object element)
		{
			
			boolean result = false;
			if (element instanceof Role)
			{
				final Role role = (Role) element;
				if (role.getActions().isEmpty() == false)
				{
					result = true;
				}

			} else if (element instanceof User)
			{
				final User role = (User) element;
				if (role.getRoles().isEmpty() == false)
				{
					result = true;
				}

			}
			return result;
		}

	}

	

	class NameSorter extends ViewerSorter
	{
	}

	/**
	 * The constructor.
	 */
	public UserView()
	{

		ss = CoreActivator.getDefault().getSecurityService();
	}

	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */

	@Override
	protected void securedCreatePartControl(Composite parent)
	{
		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
		viewer.setContentProvider(userViewContentProvider);
		ss.addListener(userViewContentProvider);
		viewer.setLabelProvider(new AuthorityLabelProvider());
		viewer.setSorter(new NameSorter());
		viewer.setInput(getViewSite());

		getSite().setSelectionProvider(viewer);
		getViewSite().setSelectionProvider(viewer);

		getSite().getPage().addSelectionListener(new ISelectionListener()
		{

			@Override
			public void selectionChanged(IWorkbenchPart arg0, ISelection arg1)
			{
				System.out.println("selection  changed");
				getSite().setSelectionProvider(viewer);
			}

		});
		// getViewSite().setSelectionProvider(viewer);

		// Create the help context id for the viewer's control
		PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "com.spx.core.starttypes.viewer");

		hookContextMenu();
		contributeToActionBars();
	}

	@Override
	public void init(IViewSite site) throws PartInitException
	{
		System.out.println("site name" + site.getRegisteredName());
		super.init(site);
	}

	@Override
	public void dispose()
	{
		ss.removeListener(userViewContentProvider);
		super.dispose();
	}

	private void hookContextMenu()
	{
		final MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener()
		{
			public void menuAboutToShow(IMenuManager manager)
			{
				UserView.this.fillContextMenu(manager);
			}
		});
		final Menu menu = menuMgr.createContextMenu(viewer.getControl());

		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars()
	{
		final IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager)
	{
		// manager.add(addUserAction);
		// manager.add(new Separator());

	}

	private void fillContextMenu(IMenuManager manager)
	{
		// manager.add(addUserAction);

		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}

	private void fillLocalToolBar(IToolBarManager manager)
	{
		// manager.add(addUserAction);

	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	@Override
	public void setFocus()
	{
		viewer.getControl().setFocus();
	}


	
	
}